package sma.trabajoFinal.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

public class ClienteJpaController implements Serializable {

	private static final long serialVersionUID = 1L;
	
	public ClienteJpaController(EntityManagerFactory emf) {
		this.emf = emf;
	}
	private EntityManagerFactory emf = null;

	public EntityManager getEntityManager() {
		return emf.createEntityManager();
	}

	public void create(Cliente cliente)	throws Exception {
		EntityManager em = null;
		try {
			em = getEntityManager();
			em.getTransaction().begin();
			em.persist(cliente);
			em.getTransaction().commit();
		} catch (Exception ex) {
			throw ex;
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}

	public void edit(Cliente cliente)
			throws /*NonexistentEntityException,*/Exception {
		EntityManager em = null;
		try {
			em = getEntityManager();
			em.getTransaction().begin();
			cliente = em.merge(cliente);
			em.getTransaction().commit();
		} catch (Exception ex) {
			/*String msg = ex.getLocalizedMessage();
			if (msg == null || msg.length() == 0) {
			    Integer id = cliente.getId();
			    if (findCliente(id) == null) {
			        throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.");
			    }
			}*/
			throw ex;
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}

	public void destroy(Cliente cliente)
			throws /*NonexistentEntityException, */Exception {
		EntityManager em = null;
		try {
			em = getEntityManager();
			em.getTransaction().begin();
			Cliente obj;
			try {
				obj = em.getReference(Cliente.class, cliente.getIdCliente());
				//obj.getId();
			} catch (Exception e) {
				throw new Exception("The cliente with id "
						+ cliente.getIdCliente() + " no longer exists.", e);
			}
			em.remove(obj);
			em.getTransaction().commit();
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}

	public List<Cliente> findClienteEntities() {
		return findClienteEntities(true, -1, -1);
	}

	public List<Cliente> findClienteEntities(int maxResults, int firstResult) {
		return findClienteEntities(false, maxResults, firstResult);
	}

	private List<Cliente> findClienteEntities(boolean all, int maxResults,
			int firstResult) {
		EntityManager em = getEntityManager();
		try {
			CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
			cq.select(cq.from(Cliente.class));
			Query q = em.createQuery(cq);
			if (!all) {
				q.setMaxResults(maxResults);
				q.setFirstResult(firstResult);
			}
			return q.getResultList();
		} finally {
			em.close();
		}
	}

}
